package com.mjduan.myBank.myPayment.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.mjduan.myBank.myPayment.service.IMyPayService;
import com.mjduan.myBank.util.dateUtil.DateUtil;
import com.mjduan.myBank.util.entity.MyPay;
import com.mjduan.myBank.util.entity.User;
import com.mjduan.myBank.util.excelUtil.ExcelDataFormatException;
import com.mjduan.myBank.util.excelUtil.ExcelUtil;
import com.mjduan.myBank.util.logger.MyLogger;
import com.mjduan.myBank.util.property.MyProperty;


/**
 * MyPay对应的controller
 * 
 * @author Duan
 *
 */
@Controller
@RequestMapping("/myPayment/MyPayController")
public class MyPayController {
	
	@Autowired
	@Qualifier("MyPayServiceImpl")
	private IMyPayService iMyPayService;

	@RequestMapping(value="addPay",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> addPay(@ModelAttribute MyPay myPay,
			HttpServletRequest request){
		if(myPay.getRemark()!=null){
			myPay.setRemark(myPay.getRemark().trim());
		}
		
		Map<String,Object> map=new HashMap<String, Object>();
        
		//下面这条语句会出现null指针异常的
		User user = (User) request.getSession().getAttribute(MyProperty.MY_SESSION);
		if(user==null){
			MyLogger.error("session失效了");
		}
		
		myPay.setUser(user);
		myPay.setTime(DateUtil.getCurrentDateStr());
		
		//Out.println(myPay.toString());
		
		if(this.iMyPayService.addMyPay(myPay)){
			map.put(MyProperty.STATUS, MyProperty.SUCCESS);
		}else{
			String fail_message = "添加支出失败";
			map.put(MyProperty.STATUS, MyProperty.FAIL);
			map.put(MyProperty.FAIL_MESSAGE, fail_message);
		}
		
		return map;
	}
	
	/**
	 * 获取数据库中支出的总金额
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getSumOfMoney")
	@ResponseBody
	public Map<String,Object> getSumOfMoney(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		
		String sumOfMoney = this.iMyPayService.getSumOfMoney();
		
		map.put(MyProperty.STATUS, MyProperty.SUCCESS);
		map.put("sumOfMoney", sumOfMoney);
		
		return map;
	}
	
	@RequestMapping(value="getMyPayWithLimit")
	@ResponseBody
	public  Map<String,Object> getMyPayWithLimit(@RequestParam("index") int index,
			HttpServletRequest request){
		
		
		Map<String,Object> map=new HashMap<String, Object>();
		
		long countOfRows = 0;
		if(request.getSession()!=null){
			Object obj = request.getSession().getAttribute(MyProperty.COUNT_OF_ROWS);
			if(obj!=null){
				countOfRows = (Long)obj;
			}
		}		
		
        if(countOfRows==0){
        	//OutUtil.println("count:"+countOfRows);
        	countOfRows = this.iMyPayService.getCount();
        	request.getSession().setAttribute(MyProperty.COUNT_OF_ROWS, countOfRows);
        }
        
        int offset=((index-1)<=0?0:(index))*MyProperty.ITEMS_PER_PAGE;
        List<MyPay> myPays = this.iMyPayService.getMyPayWithLimit(offset, MyProperty.ITEMS_PER_PAGE);
		
        map.put(MyProperty.STATUS, MyProperty.SUCCESS);
        map.put(MyProperty.COUNT_OF_ROWS, countOfRows);
        map.put("myPays", myPays);
        
		return map;
	}
	
	/**
	 * 处理excel文件上传
	 * 
	 * @param request
	 * @param response
	 * @param modelAndView
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/uploadExcel",method=RequestMethod.POST)
	public ModelAndView uploadExcel(HttpServletRequest request,
			HttpServletResponse response,ModelAndView modelAndView) throws UnsupportedEncodingException{
		request.setCharacterEncoding(MyProperty.UTF_8);
        
		handleUploadExcel(request);
		
		modelAndView.setViewName("forward:/user/UserController/main");
		return modelAndView;
	}
	
	/**
	 * 处理excel文件上传
	 * 
	 * @param request
	 * @return
	 */
	private boolean handleUploadExcel(HttpServletRequest request){
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		
		//用完之后怎么将这个文件删除???
		MultipartFile multipartFile = multipartHttpServletRequest.getFile("myfile");
		
		String[] obj = {"0","1","2"};
		try {
			List<Object[]> list = ExcelUtil.readDataFromExcelWithPoi(multipartFile.getInputStream(), 0, obj);
		    
			User user = (User) request.getSession().getAttribute(MyProperty.MY_SESSION);
			return this.iMyPayService.addPayFromExcel(list, user);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			return false;
		} catch (ExcelDataFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	@RequestMapping(value="getAllMyPayWithoutRemark")
	@ResponseBody
	public  Map<String,Object> getAllMyPayWithoutRemark(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String, Object>();
		
		try {
			//下面这条语句有时候会触发空指针异常，所以放在try...catch..中
			User user = (User) request.getSession().getAttribute(MyProperty.MY_SESSION);
			
			List<MyPay> myPays = this.iMyPayService.getAllMyPayWithoutRemark(user);
			map.put(MyProperty.STATUS, MyProperty.SUCCESS);
			map.put("myPays", myPays);
		} catch (Exception e) {
			// TODO: handle exception
			map.put(MyProperty.STATUS, MyProperty.FAIL);
			map.put(MyProperty.FAIL_MESSAGE, "服务器端出现错误,请重新登录之后重试!");
		}
		
		return map;
	}
	
	
	//public List<MyPay> getAllMyPayWithoutRemark(User user);
}
